package com.zmx.b2c.order.messaging.listener;

import com.nepxion.aquarius.cache.annotation.CacheEvict;
import com.zmx.common.common.contents.cache.OrderCacheContents;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Component;

/**
 * @Description: 清除订单缓存基类
 * @ClassName: DeleteOrderCachePartent
 * @Author zhaomxr
 * @Date 2021-10-26 14:42
 */
@Slf4j
@Component
public class DeleteOrderCacheParent {

    @Autowired
    private RedisTemplate redisTemplate;

    @Value("${prefix}")
    private String prefix;

    public void onMessage(@Payload String orderCode) {
    }

    public void deleteKey(String orderCode) {
        if (!StringUtils.isEmpty(orderCode)) {
            Object obj = redisTemplate.opsForValue().get(prefix + "_" + OrderCacheContents.ORDER + "_" + orderCode);
            if (obj != null) {
                //清除redis缓存
                clear();
            }
        }
    }

    /**
     * 基于@CacheEvict注解方式清除指定key
     */
    @CacheEvict(name = OrderCacheContents.ORDER, key = "#p0", allEntries = false, beforeInvocation = false)
    private void clear() {

    }

    /**
     * 基于原生redis清除指定key
     * @param orderCode
     */
    public void clear(String orderCode) {
        redisTemplate.delete(prefix + "_" + OrderCacheContents.ORDER + "_" + orderCode);
    }
}
